import '../lib/wangeditor/dist/css/style.css'
import { createEditor, createToolbar } from '../lib/wangeditor/dist/index.min.js'
import {defZFormFieldCom} from "@/zform/render";

let editorMap = new Map()

function parseHtml(html = '') {
  let parser = new DOMParser();
  let b = parser.parseFromString(html, 'text/html');
  let all = b.body.getElementsByTagName("*");
  // console.log( Array.of(...all))
  Array.of(...all).forEach(ele => {
    let className = 'w-e-' + ZY.lodash.kebabCase(ele.tagName)
    if (!ele.classList.contains(className)) {
      ele.classList.add(className)
    }
    // ele.classList.add('w-e-' + ZY.lodash.kebabCase(ele.tagName))
  })
  return b.body.innerHTML
}

defZFormFieldCom('CusRichEditor', {
  create(propConfig,props,extData) {
    return {
      template: `
        <div class="z-wang-editor">
<!--            {{value}}-->
        <div :id="toolbarID"></div>
        <div :id="editorID"></div>
        </div>
      `,
      mixins: [

      ],
      watch: {
        value(newVal) {
          let editor = editorMap.get(this.editorID)
          console.log('CusRichEditor', this.locked, editor, newVal)
          if (!this.locked) {
            if (editor) {
              setTimeout(() => {
                editor.dangerouslyInsertHtml(newVal)
              }, 100)
            } else {
              console.log('no editor')
            }
          }
        }
      },
      data() {
        // console.log(extData)
        return {
          value: undefined,
          ui: propConfig.ui,
          ...extData,
          toolbarID: 'toolbar__' + ZY.rid(),
          editorID: 'editor__' + ZY.rid(),
          editorConfig: {},
          locked: false,
          editor: null,
        }
      },
      mounted() {
        let self = this
        this.editorConfig.onChange = (editor) => {
          self.locked = true
          let html = parseHtml(editor.getHtml());
          console.log('html', html)
          self.zfield__onInput(html);
          setTimeout(() => {
            self.locked = false
          }, 100)
        }

        let editor = createEditor({
          selector: "#" + this.editorID,
          config: this.editorConfig,
          content: '', // 默认内容，下文有解释
          // mode: 'simple' // 或者 'simple' ，下文有解释
        });



        let toolbar = createToolbar({
          editor: editor,
          selector: '#' + this.toolbarID,
          // config: toolbarConfig,
          // mode: 'simple' // 或者 'simple' ，下文有解释
        })

        editorMap.set(this.editorID, editor)
      },
      beforeUnMount() {
        editorMap.delete(this.editorID)
      }
    }
  }
})
